import { Title } from '@/components/common/Title'
import { useEffect, useState } from 'react'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import BroadcastControl from './components/BroadcastControl'
import ConfigDialog from './components/ConfigDialog'
import ContentRewriteCard from './components/ContentRewriteCard'
import { SmartReplyService } from './components/SmartReplyService'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useAccounts } from '@/hooks/useAccounts'
import CommentList from '@/pages/AutoReply/components/CommentList'
import LogDisplayer from '@/components/common/LogDisplayer'
import { Button } from '@/components/ui/button'
import { Settings2 } from 'lucide-react'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'

export default function AIAssist() {
  const { handleCommentBroadcast, isBroadcasting } = useAIAssist()
  const { currentAccountId } = useAccounts()
  const [configDialogOpen, setConfigDialogOpen] = useState(false)

  // 监听评论事件，触发播报
  useEffect(() => {
    // ✅ 只有在播报启用时才监听评论事件
    if (!isBroadcasting) {
      return
    }

    const unsubscribe = window.ipcRenderer.on(
      IPC_CHANNELS.tasks.autoReply.showComment,
      (data: { comment: DouyinLiveMessage; accountId: string }) => {
        if (data.accountId === currentAccountId) {
          handleCommentBroadcast(data.comment, currentAccountId)
        }
      },
    )

    return () => {
      unsubscribe()
    }
  }, [currentAccountId, handleCommentBroadcast, isBroadcasting])

  return (
    <div className="container py-8 space-y-6">
      {/* AI智能语音回复服务（后台运行，不显示UI） */}
      <SmartReplyService />
      
      <div>
        <Title title="AI助播" description="智能AI助理协助直播，自动播报用户评论" />
      </div>

      {/* 播报控制 */}
      <Card className="shadow-sm">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>任务控制</CardTitle>
              <CardDescription>启动评论监听和AI助播任务</CardDescription>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setConfigDialogOpen(true)}
            >
              <Settings2 className="h-4 w-4 mr-1" />
              全局设置
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <BroadcastControl />
        </CardContent>
      </Card>

      {/* 内容改写播放和评论列表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 内容改写播放 */}
        <ContentRewriteCard />

        {/* 评论列表 */}
        <CommentList highlight={null} />
      </div>

      {/* 运行日志 */}
      {/* <Card className="shadow-sm">
        <div className="h-96">
          <LogDisplayer />
        </div>
      </Card> */}

      {/* 配置弹窗 */}
      <ConfigDialog
        open={configDialogOpen}
        onOpenChange={setConfigDialogOpen}
      />
    </div>
  )
}


